<?php
namespace app\common\logic;

use think\Db;
class CateLogic
{

	private function M()
	{
		return M('cate');
	}


	public function ls($module)
	{
		$_GET['site'] = request()->header('site-id');
		$_GET['module'] = $module;
		$data = $this->M()->parseWhere()->select();
		//转为树，再转回列表，这是为了保证子类在父类的下方。前方显示时利用lv生成层级样式
		$data = list_to_tree($data);
		$list = array();
		tree_to_list($data, '_sub', 'id', $list);
		return $list;
	}

	public function get($id)
	{
		$id = (int) $id;
		$row = $this->M()->find($id);
		$row['custom'] = json_decode($row['custom'], true);
		if(!is_array($row['custom'])) $row['custom'] = array();
		return $row;
	}

	public function save($post)
	{
		$id = (int) $post['id'];
		if($id) {
			$rs = $this->M()->update($post);
			if($rs !== false) {
				return true;
			}
		}else{
			$rs = $this->M()->insert($post);
			if($rs !== false) {
				return true;
			}
		}
		error('保存错误');
	}

	public function del($id)
	{
		$id = (int) $id;
		if(!$id) error('参数错误');
		$row = $this->M()->where('id', $id)->find();

		$has_sub = $this->M()->where(['pid' => $id])->find();

		if($has_sub) error('有子分类，不可删除，请先删除子分类');

		if($row['module']) {
			$count = M($row['module'])->where('cate_id', $id)->count();
			if($count){
				error('分类下有内容，不可删除，请先删除分类中的内容');
			}
		}

		$rs = $this->M()->where('id', $id)->delete();
		if($rs === false) {
			error('删除失败');
		}else{
			return true;
		}
	}

	//获取自定义字段
	public function getCustom($id)
	{
		$row = $this->get($id);
		$row['custom'] = singleGroup($row['custom'], 'en');
		return $row;
	}

	//加载分类自定义字段（会继承父类的自定义字段）
	public function custom($id)
	{
		$row = $this->getCustom($id);
		$prow = $this->getCustom($row['pid']);
		$pprow = $this->getCustom($prow['pid']);
		$custom = array_merge($pprow['custom'], $prow['custom'], $row['custom']);
		$custom = array_values($custom);
		foreach($custom as &$c) {
			$c['option'] && $c['option'] = explode("\n", $c['option']);
			$c['ext'] && $c['ext'] = explode("\n", $c['ext']);
		}
		return $custom;
	}

	//保存自定义字段
	public function save_setting($id, $post)
	{
		$rs = $this->M()->where('id', $id)->setField('custom', json_encode($post, 256));
		if($rs === false) error( '保存自定义字段失败');
		return true;
	}
}
